import axios, { AxiosAdapter ,AxiosResponse} from 'axios'
import {
	apiUrl,CURRENT_ENV,version
} from '../config'

import mpAdapter from 'axios-miniprogram-adapter'
axios.defaults.adapter = mpAdapter as AxiosAdapter

axios.defaults.timeout = 60000;

const request = axios.create({
	baseURL: apiUrl[CURRENT_ENV],
})


// 添加请求拦截器
request.interceptors.request.use(function (config) {
	var token = uni.getStorageSync('b-token')
	token="apiYKHCwipLkLqxcRpGKvTZ44ZoZvlvYXtU"
	if (!config.params) config.params = {}
	config.params.token = token
	config.params.ver = version
	return config;
}, function (error) {
	// Do something with request error

	return Promise.reject(error);
});


// 添加响应拦截器
request.interceptors.response.use((response:AxiosResponse<any>)=> {
	if (response.data.code == 401 || response.data.code == 403 ||  response.data.code == 405) {
		console.log('登录过期')
		uni.redirectTo({
			url: '/pages/login/index'
		});
		uni.removeStorageSync('token')

		return Promise.reject(response.data);
	} else if (response.data.code != 0 && (response.data.code + '').length != 9) {
		uni.showToast({
			title: response.data.message,
			icon: 'none',
			duration: 2000
		})
		return Promise.reject(response.data);
	}

	return response.data as Axios.Response;
}, function (error) {
	return Promise.reject(error);
});


export default request
